package com.kingsoft.dc.khaos.plugin.core;

import com.kingsoft.dc.khaos.plugin.core.exception.PermissionException;
import com.kingsoft.dc.khaos.plugin.core.metadata.PluginModuleConfig;
import com.kingsoft.dc.khaos.plugin.core.utils.Logging;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

/**
 * Created by jing on 19/8/1.
 */
public class AppScheduler extends Logging{
    private KhaosContext khaosContext;

    public AppScheduler(KhaosContext khaosContext) {
        this.khaosContext = khaosContext;
    }

    public void run(PluginModuleConfig moduleConfig) {
        runTask(moduleConfig);
    }

    public void runTask(PluginModuleConfig moduleConfig) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            logInfo("-----------------------------------");
            logInfo("START TIME:" + sdf.format(System.currentTimeMillis()));

            String moduleId = moduleConfig.getId();
            String clazz = moduleConfig.getClazz();

            //实例化组件
            Object moduleInstance = Class.forName(clazz).getDeclaredConstructor().newInstance();

            //init参数
            Method init = moduleInstance.getClass().getMethod("init", String.class, KhaosContext.class);
            init.invoke(moduleInstance, moduleId, khaosContext);

            //执行准备作
            Method prepare = moduleInstance.getClass().getMethod("prepare");
            prepare.invoke(moduleInstance);

            //执行逻辑方法
            Method execute = moduleInstance.getClass().getMethod("execute");
            execute.invoke(moduleInstance);

            //执行成功
            logInfo("END TIME:" + sdf.format(System.currentTimeMillis()));
            long curTime = System.currentTimeMillis();
        } catch (Exception e) {
            handleException(e);
        }
    }

    public void handleException(Exception e) {
        if (e instanceof InvocationTargetException) {
            Throwable t = ((InvocationTargetException) e).getTargetException();
            if (t instanceof PermissionException) {
                log().error(t.getMessage());
            } else {
                t.printStackTrace();
            }
        } else {
            e.printStackTrace();
        }
        System.exit(1);
    }
}
